﻿using System;
using System.Linq;
using API.IRepositories;
using API.EntityModels;
using API.Helpers;


namespace API.Repositories
{
    public class DrinkRepository : IDrinkRepository
    {
        public void Delete(int id)
        {
            var emptyEntity = new Drink() { DrinkId = id };
            using (var entityConnection = ConnectionHelper.GetEntityConnection())
            {
                entityConnection.Drinks.Attach(emptyEntity);
                entityConnection.Drinks.DeleteObject(emptyEntity);
                entityConnection.SaveChanges();
            }
        }

        public IQueryable<Drink> Get(int drinkId)
        {
        var entities = ConnectionHelper.GetEntityConnection();
        return from d in entities.Drinks
               where d.DrinkId == drinkId
               select d;
        }

        public EntityModels.Drink Save(Drink entity, Type baseEmptyEntityOnType)
        {
            using (var entityConnection = ConnectionHelper.GetEntityConnection())
            {
                if (entity.DrinkId > 0)
                {
                    var emptyEntity = EntityFrameworkHelper.BuildEmptyEntityForAttachment(entity, baseEmptyEntityOnType);
                    emptyEntity.DrinkId = entity.DrinkId;
                    entityConnection.Drinks.Attach(emptyEntity);
                    entityConnection.Drinks.ApplyCurrentValues(entity);
                }
                else
                {
                    entity = EntityFrameworkHelper.ResetEntityForAdd(entity, baseEmptyEntityOnType);
                    entity.Created = DateTime.Now;
                    entityConnection.Drinks.AddObject(entity);
                }

                entityConnection.SaveChanges();
                return Get().FirstOrDefault(d => d.DrinkId == entity.DrinkId);
            }          
        }


        public IQueryable<Drink> Get()
        {
            return ConnectionHelper.GetEntityConnection().Drinks.AsQueryable();
        }
    }
}




       